package com.zkingsoft.actions.admin;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.zkingsoft.actions.common.BaseController;
import com.zkingsoft.anotations.RemoveRequestToken;
import com.zkingsoft.anotations.SaveRequestToken;
import com.zkingsoft.exception.GlobleException;
import com.zkingsoft.model.TabClass;
import com.zkingsoft.model.Userinfo;
import com.zkingsoft.plugin.pojo.PaginationVO;
import com.zkingsoft.plugin.util.DateUtils;
import com.zkingsoft.plugin.util.ExcelImport;
import com.zkingsoft.plugin.util.ExcelUtil;
import com.zkingsoft.plugin.util.ExcelUtil.ViewExcel;
import com.zkingsoft.plugin.util.FileDownload;
import com.zkingsoft.plugin.util.FileUtils;
import com.zkingsoft.plugin.util.WebUtil;
import com.zkingsoft.pojo.AjaxResult;
import com.zkingsoft.serviceUtil.ServiceUtil;
import com.zkingsoft.services.TabClassService;
import com.zkingsoft.services.UserinfoService;

/**
 * 班级
 * @date 2016-12-16 16:41
 */
@Controller
@RequestMapping(value = "admin/tabClass")
public class TabClassController extends BaseController{

	@Resource
	private TabClassService tabClassService;
	@Resource
	private UserinfoService userinfoService;
	@Resource
	private ServiceUtil serviceUtil;
	/**
	 * @Description:查询所有的班级
	 * @author:dingchuan
	 * @return
	 * 返回类型 AjaxResult
	 * @date 2016年12月17日
	 */
	@RequestMapping(value = "/showAllClass")
	public @ResponseBody AjaxResult showAllClass() {
 		List<TabClass> classList = tabClassService.findByModel(null);
 		if(classList!=null && classList.size()>0){
 			return new AjaxResult(AjaxResult.STATUS_OK,null,"成功",classList,classList.size());
 		}
 		return new AjaxResult(AjaxResult.STATUS_ERR,null,"失败");
	}
	
	
	/**
	 * 列表显示
	 */
	@RequestMapping(value = "/showList")
	public @ResponseBody AjaxResult showList(TabClass tabClass, PaginationVO pageVo) {
		pageVo.setOrder("desc");
		pageVo.setSort("cla_date");
		return showList(tabClassService, tabClass, pageVo);
	}
   	
	/**
	 * 新增或者修改页面
	 */   
	@RemoveRequestToken	
   	@RequestMapping(value = "/addOrModify")
	public @ResponseBody AjaxResult addOrModify(TabClass tabClass) {
		
		if (tabClass.getClaId() != null) {
			return modify(tabClassService, tabClass, "班级");
		} else {
			//判断班级名称是否存在
			if (serviceUtil.addCheckRepeat("tab_class", "cla_name", tabClass.getClaName())){
			      throw new GlobleException("该班级名称已经存在");
			}
			return add(tabClassService, tabClass, "班级");
		}
	}
	
   	/**
	 * 进入修改界面
	 */   
	@SaveRequestToken
   	@RequestMapping(value = "/editForm")
	public String editForm(Long id) {
		TabClass tabClass;
		if (id != null) {
			tabClass = tabClassService.findById(id);
			WebUtil.getRequest().setAttribute("obj", tabClass);
		}
		return "admin/class-form";
	}
   	
   	
   	/**
	 * 删除
	 */  
 	@RequestMapping(value = "/del")
	public @ResponseBody AjaxResult del(String keys) {
		return remove(tabClassService, keys);
	}
 	
 	/*
 	 * 查询所有的员工
 	 */
 	@RequestMapping(value = "/showAllUserInfo")
	public @ResponseBody AjaxResult showAllUserInfo() {
		List<Userinfo> users = userinfoService.findByModel(null); 
 		if(users!=null && users.size()>0){
 			return new AjaxResult(AjaxResult.STATUS_OK,null,"查询成功",users,users.size());
 		}
 		return new AjaxResult(AjaxResult.STATUS_OK,null,"查询失败");
	}
 	
 	/**
 	 * 
 	 * @Description:导出excel
 	 * @author:dingchuan
 	 * @return
 	 * 返回类型 ModelAndView
 	 * @date 2017年2月13日
 	 */
 	@RequestMapping(value = "/exportExcel")
 	public @ResponseBody ModelAndView report(ModelMap model, HttpServletRequest request, HttpServletResponse response,
 			TabClass tabClass) {
 	    try {
 	        if (tabClass.getClaName() != null && !(tabClass.getClaName().equals(""))) {
 	        	tabClass.setClaName(java.net.URLDecoder.decode(tabClass.getClaName(), "UTF-8"));
 	        }
 	    } catch (UnsupportedEncodingException e1) {
 	        e1.printStackTrace();
 	    }
 	    // 查询符合条件的数据
 	    List<TabClass> dataList = tabClassService.findByModel(tabClass);
 	    //把数据组装成我们要的数据，外面的list表示一行数据，也就是一个对象的信息，对应到excel的一行数据。里面的list表示对象的一个属性，对应excel的单元格
 	    SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_FORMAT_DD);
 	    List<List< Object>> list = new ArrayList<>();
 	        for (TabClass obj : dataList) {
 	            List<Object> temp = new ArrayList<>();
 	            temp.add(obj.getClaName());
 	            temp.add(obj.getHeadmasterName());
 	            temp.add(obj.getTeacherName());
 	            String dateStr = sdf.format(obj.getClaDate());
 	            temp.add(dateStr);
 	            temp.add(obj.getClaRemark());
 	            list.add(temp);
 	        }
 	         
 	        //调用我们的excel工具类，导出数据
 	    HSSFWorkbook workbook = ExcelUtil.generateExcel("班级列表",
 	            new String[] { "班级名称","班主任姓名","教师姓名","开班时间","备注"}, list);
 	    try {
 	        ViewExcel.buildExcel(null, workbook, request, response, "班级列表.xls");
 	    } catch (Exception e) {
 	        e.printStackTrace();
 	    }
 	    return new ModelAndView(new ViewExcel(), model);
 	}
 	
 	/**
 	 * @Description:下载模板
 	 * @author:dingchuan
 	 * @param response
 	 * @throws Exception
 	 * 返回类型 void
 	 * @date 2017年2月14日
 	 */
 	@RequestMapping(value="/downExcelModel")
   	public void downExcelModel(HttpServletResponse response) throws Exception{
   		String path = WebUtil.getResourceRealPath("WEB-INF/views/admin/class_import_model.xlsx");   		
   		FileDownload.fileDownload(response, path, "班级导入模板.xlsx");
   	}
 	
	private static final Logger log = Logger.getLogger(TabClassController.class);
 	
 	/**
 	 * @Description:导入excel
 	 * @author:dingchuan
 	 * @param response
 	 * @param request
 	 * @param file
 	 * @return
 	 * 返回类型 AjaxResult
 	 * @date 2017年2月14日
 	 */
 	@RequestMapping(value = "/importData")
	public @ResponseBody AjaxResult importData(HttpServletResponse response, HttpServletRequest request,
			@RequestParam(value = "file", required = false) MultipartFile file) {
		// 记录成功的导入多少条数据
		int count = 0;
		// 构造对象的集合
		List<TabClass> tabClassList = new ArrayList<TabClass>();
		response.setContentType("text/html;charset=UTF-8");
		String fileName = file.getOriginalFilename();
		String extension = fileName.lastIndexOf(".") == -1 ? "" : fileName.substring(fileName.lastIndexOf(".") + 1);
		if (!extension.equals("xls") && !extension.equals("xlsx")) {
			return new AjaxResult(AjaxResult.STATUS_OK, null, "请选择excel文件！！！");
		}
		String dirPath = request.getSession().getServletContext().getRealPath("/") + "fileupload";
		File fileDir = new File(dirPath);
		SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_FORMAT_DD);
		try {
			if (!fileDir.exists()) {
				if (fileDir.mkdirs()) {
				}
			}
			File saveFile = new File(dirPath + "/" + fileName);
			file.transferTo(saveFile);
			List<List<Object>> list = ExcelImport.readExcel(saveFile, fileName, null, 4);
			// 由于读取excel的工具类会从标题行开始读取，因此，list=null或者size=1表示只有标题行说明没有数据可以导入
			if (list == null || list.size() <= 1) {
				throw new GlobleException("没有数据可导入");
			}
			for (int i = 1; i < list.size(); i++) {
				TabClass tabClass = new TabClass();//每一行
				List<Object> objList = list.get(i);
				int t = i+1;
				if(objList.get(0)==null){
   	   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的班级名称没有填写");
   	   			}else{
   	   				String className = ((String)objList.get(0)).trim();//班级名称
   	   				tabClass.setClaName(className);
   	   			}
				
				
				if(objList.get(1)==null){
   	   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的班主任工号没有填写");
   	   			}else{
   	   				String claHeadmasterNo = ((String)objList.get(1)).trim();//班主任工号
   	   				Userinfo staff = userinfoService.findByNo(claHeadmasterNo);
   	   				if(staff == null){
   	   					return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的班主任工号不存在");
   	   				}
   	   				tabClass.setClaHeadmaster(staff.getuId()); 	   			
   	   			}
				
				if(objList.get(2)==null){
   	   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的教师工号没有填写");
   	   			}else{
   	   				String claHeadmasterNo = ((String)objList.get(2)).trim();//教师工号
   	   				Userinfo staff = userinfoService.findByNo(claHeadmasterNo);
   	   				if(staff == null){
   	   					return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的教师工号不存在");
   	   				}
   	   				tabClass.setClaTeacher(staff.getuId()); 	   			
   	   			}
				
				
				if(objList.get(3)==null){
   	   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的开班时间没有填写");
   	   			}else{
   	   				String claDateStr = ((String)objList.get(3)).trim();//开班时间
   	   				Date date;
   	   				try {
   	   					date = sdf.parse(claDateStr);
					} catch (Exception e) {
						log.debug(e.toString());
		   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的开班时间填写格式不正确");
					}
   	   				tabClass.setClaDate(date);
   	   			}
				tabClass.setClaRemark((String)objList.get(4));
				//判断班级名称是否存在
				if (serviceUtil.addCheckRepeat("tab_class", "cla_name", tabClass.getClaName())){
				      throw new GlobleException("导入失败!因为第"+t+"行的班级名称已经存在");
				}
				tabClassList.add(tabClass);
			}
			count =	tabClassService.adds(tabClassList);
		} catch (IOException e) {
			log.error("导入异常");
		}finally {
			FileUtils.deleteDir(fileDir);
		}
		if (count > 0) {
			return new AjaxResult(AjaxResult.STATUS_OK, null, "成功导入" + count + "条数据!");
		} else {
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!");
		}
	}
}